<template>
  <div class="contents-container">
    <div class="search-area">
      <span class="lable-span"><i class="el-icon-search" /> 手机号</span>
      <el-input v-model="listQuery.perAccount" style="width: 180px;" size="mini" placeholder="请输入用户进行查询" @change="getListData" />
      <span class="lable-span"><i class="el-icon-search" /> 用户</span>
      <el-input v-model="listQuery.perName" style="width: 180px;" size="mini" placeholder="请输入用户进行查询" @change="getListData" />
      <span class="lable-span"><i class="el-icon-search" /> 用户类型</span>
      <el-select v-model="listQuery.perType" size="mini" style="width: 180px;" placeholder="请选择类型" @change="getListData">
        <el-option label="全部" :value="allValue" />
        <el-option v-for="item in typeList" :key="item.SubNum" :label="item.SubName" :value="item.SubNum" />
      </el-select>
      <el-button size="mini" class="ml-15" type="primary" @click="getListData">查询</el-button>
      <el-button size="mini" class="ml-15" @click="research">重置</el-button>
      <el-button size="mini" class="ml-15" type="success" @click="addData">新增</el-button>
    </div>
    <!-- 列表 -->
    <el-table :data="listData" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="用户名称" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.perName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户头像" align="center" width="100" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-image v-if="scope.row.portrait" contain :src="$urlHost+scope.row.portrait" :preview-src-list="srcList" alt="" @click="gteImgList($urlHost+scope.row.portrait)" />
        </template>
      </el-table-column>
      <el-table-column label="用户角色" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.perType == 0?'管理':scope.row.perType == 1?'师傅':scope.row.perType == 2?'监理':scope.row.perType == 3?'业主':scope.row.perType == 4?'设计师':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.perAccount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="性别" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.perGx == 0?'男':scope.row.perGx == 1?'女':scope.row.perGx == 2?'未知':'' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.perAge }}</span>
        </template>
      </el-table-column>
      <el-table-column label="从业经验" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.experience }}</span>
        </template>
      </el-table-column>
      <el-table-column label="籍贯">
        <template slot-scope="scope">
          <span>{{ scope.row.perBirthpace }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleGetDetail(scope.row.userId)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDeleted(scope.row.userId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/修改 -->
    <PopWindow v-show="showForm" :title="title" :mode="modeValue" @close="closeForm" @addHandle="addHandle" @updateHandle="updateHandle">
      <el-form ref="formData" :model="formData" label-width="100px" size="small" :rules="formDataRules">
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号" prop="perAccount">
              <el-input v-model="formData.perAccount" class="my-input" />
            </el-form-item>
            <el-form-item label="性别" prop="perGx">
              <el-select v-model="formData.perGx" placeholder="请选择性别" style="width:100%;">
                <el-option v-for="item in sexList" :key="item.SubNum" :label="item.SubName" :value="item.SubNum" />
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="perType">
              <el-select v-model="formData.perType" placeholder="请选择角色" style="width:100%;" :disabled="modeValue=='edit'">
                <el-option v-for="item in typeList" :key="item.SubNum" :label="item.SubName" :value="item.SubNum" />
              </el-select>
            </el-form-item>
            <el-form-item label="从业经验" prop="experience">
              <el-input v-model="formData.experience" class="my-input" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="perName">
              <el-input v-model="formData.perName" class="my-input" />
            </el-form-item>
            <el-form-item label="年龄" prop="perAge">
              <el-input v-model="formData.perAge" class="my-input" />
            </el-form-item>
            <el-form-item label="籍贯" prop="perBirthpace">
              <el-input v-model="formData.perBirthpace" class="my-input" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="头像" prop="portrait">
          <el-upload
            class="avatar-uploader"
            :action="$uploadImg"
            :show-file-list="false"
            :with-credentials="true"
            name="files"
            accept="image/png, image/jpeg"
            :on-success="handleLisenceSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="formData.portrait" :src="$urlHost + formData.portrait" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" style="border: 1px dashed #d9d9d9;" />
            <el-tooltip class="item" effect="dark" content="只能上传jpg/png文件，且不超过10MB" placement="top">
              <i class="el-icon-question" style="padding-left:5px;" />
            </el-tooltip>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" class="my-input" />
        </el-form-item>
      </el-form>

    </PopWindow>
    <pagination
      v-show="total > 0"
      :total="total"
      :page-index.sync="listQuery.pageIndex"
      :page-size.sync="listQuery.pageSize"
      @pagination="getListData"
    />
  </div>
</template>

<script>
	import Pagination from '@/components/Pagination'
	import PopWindow from '@/components/PopWindow'
	import {
		addUser,
		editUser,
		deleteUser,
		getUserList,
		getUserDetail
	} from '@/api/user'

	export default {
		name: 'Member',
		components: {
			Pagination,
			PopWindow
		},
		data() {
			return {
				allValue: -1,
				editable: false, // 日期选择器不可手动写入
				total: 0, // 总数
				listData: [],
        srcList: [],
				typeList: [{
						SubName: '管理员',
						SubNum: 0
					},
					{
						SubName: '师傅',
						SubNum: 1
					}, {
						SubName: '监理',
						SubNum: 2
					},
					{
						SubName: '业主',
						SubNum: 3
					}, {
						SubName: '设计师',
						SubNum: 4
					}
				],
				sexList: [{
						SubName: '男',
						SubNum: 0
					},
					{
						SubName: '女',
						SubNum: 1
					},
					{
						SubName: '未知',
						SubNum: 2
					}
				],
				listQuery: {
					pageIndex: 1, // 当前页码
          pageSize: 10, // 每页数量
					perAccount: '', // 用户号码
					perName: '', // 用户姓名
					perType: -1 // 用户角色
				},
				showForm: false, // 新增修改弹窗显示否
				dialogStatus: '', // 弹窗状态
				title: '用户新增',
				modeValue: 'add',
				formData: {
					perAccount: '', // 用户手机号
					perName: '', // 用户姓名
					perGx: 0, // 性别
					perAge: '', // 年龄
					perType: 0, // 关联角色
					perBirthpace: '', // 籍贯
          portrait: '', // 头像
          experience: '', // 从业经验
					remark: '' // 备注
				},
				// 表单验证规则
				formDataRules: {
					perAccount: [{
							required: true,
							message: '请输入手机号',
							trigger: 'blur'
						},
						this.$va_Mobile
					],
					perName: [{
							required: true,
							message: '请输入姓名',
							trigger: 'blur'
						},
						{
							max: 50,
							message: '50个字内',
							trigger: 'blur'
						}
					],
					perAge: {
						max: 50,
						message: '50个字内',
						trigger: 'blur'
					},
					perBirthpace: {
						max: 50,
						message: '50个字内',
						trigger: 'blur'
					},
					remark: {
						max: 200,
						message: '请输入1-200个字',
						trigger: 'blur'
					}
				}
			}
		},
		mounted() {
			this.getListData()
		},
		methods: {
			getListData(page) {
				const that = this
				that.$loadings()
				// that.listQuery.pageIndex = page||1
				getUserList(that.listQuery).then((res) => {
					that.$loadings().close()
					that.listData = res.data
					that.currentPage = page
					that.total = res.count
				}).catch((err) => {
					that.$loadings().close()
					console.log(err)
				})
			},
			resetData() {
				this.formData = {
					perAccount: '', // 用户手机号
					perName: '', // 用户姓名
					perGx: 0, // 性别
					perAge: '', // 年龄
					perType: 0, // 关联角色
					perBirthpace: '', // 籍贯
					remark: '' // 备注
				}
			},
			research() {
				this.listQuery = {
					// pageIndex: 1, // 当前页码
					// pageSize: 10, // 每页数量
					perAccount: '', // 用户号码
					perName: '', // 用户姓名
					perType: -1 // 用户角色
				}
				this.getListData()
			},
			addData() {
				this.title = '用户新增'
				this.modeValue = 'add'
				this.formData = {
					perAccount: '', // 用户手机号
					perName: '', // 用户姓名
					perGx: 0, // 性别
					perAge: '', // 年龄
					perType: 0, // 关联角色
					perBirthpace: '', // 籍贯
          portrait: '', // 头像
          experience: '', // 从业经验
					remark: '' // 备注
				}
				this.showForm = true
			},
      // 图片上传成功回调
			handleLisenceSuccess(res, file) {
				this.imgLoding.close()
				this.$message({
					type: 'success',
					message: '上传成功!'
				})
				this.uploadImg = this.$urlHost + res.data[0] // 前台展示 绝对路径
				this.formData.portrait = res.data[0] // 后台接受 相对路径
			},
			// 图片上传前回调
			beforeUpload(file) {
				this.imgLoding = this.$loading({
					lock: true,
					text: '图片上传中···',
					spinner: 'el-icon-loading',
					background: 'rgba(255, 255, 255, 0.4)'
				})
				const isPNG = file.type === 'image/png'
				const isJPG = file.type === 'image/jpeg'
				const isLt2M = file.size / 1024 / 1024 < 10

				if (!isPNG && !isJPG) {
					this.$message.error('上传图片只能是 PNG或JPG 格式!')
					this.imgLoding.close()
				}
				if (!isLt2M) {
					this.$message.error('上传图片大小不能超过 10MB!')
					this.imgLoding.close()
				}
				return (isPNG || isJPG) && isLt2M
			},
      gteImgList(url) {
				this.srcList = []
				this.srcList.push(url)
			},
			addHandle() {
				var that = this
				that.$refs.formData.validate(valid => {
					if (valid) {
						that.$loadings()
						addUser(that.formData).then(data => {
							that.$loadings().close()
							that.$message({
								type: 'success',
								message: '操作成功!'
							})
							that.research()
							that.closeForm() // 重置表单
						}).catch(error => {
							that.$loadings().close()
							that.closeForm() // 重置表单
							console.log(error)
						})
					} else {
						return false
					}
				})
			},
			closeForm() {
				if (this.$refs.formData) {
					this.$refs.formData.resetFields()
				}
				this.showForm = false
			},
			handleGetDetail(id) {
				const that = this
				that.$loadings()
				getUserDetail(id).then((res) => {
					that.$loadings().close()
					that.formData = {
						userId: res.data.userId,
						perAccount: res.data.perAccount,
						perName: res.data.perName,
						perGx: res.data.perGx,
						perAge: res.data.perAge + '',
						perType: res.data.perType,
						perBirthpace: res.data.perBirthpace,
            portrait: res.data.portrait,
            experience: res.data.experience,
						remark: res.data.remark
					}
					this.title = '用户修改'
					this.modeValue = 'edit'
					this.showForm = true
				}).catch((err) => {
					that.$loadings().close()
					console.log(err)
				})
			},
			updateHandle() {
				var that = this
				that.$refs.formData.validate(valid => {
					if (valid) {
						that.$loadings()
						editUser(that.formData).then(data => {
							that.$loadings().close()
							that.$message({
								type: 'success',
								message: '操作成功!'
							})
							that.research()
							that.closeForm() // 重置表单
						}).catch(error => {
							that.$loadings().close()
							that.closeForm() // 重置表单
							console.log(error)
						})
					} else {
						return false
					}
				})
			},
			handleDeleted(id) {
				const that = this
				that.$confirm('是否删除该条数据?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.$loadings()
					deleteUser({
						userId: id
					}).then((res) => {
						that.$loadings().close()
						that.getListData()
					}).catch((err) => {
						that.$loadings().close()
						console.log(err)
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
}
</style>
